<?php

function create_link($key, $vars) {
	global $_LINKS;
	$template = $_LINKS[$key];
	extract($vars, EXTR_OVERWRITE);
	eval("\$link = \"$template\";");
	return $link;
}
                        
/**
* 打印错误提示页面
*
* @access public
* @param string $error 错误信息
*/
function display_error($error = "") {
	$tpl_error = new smartTemplate("display_error.htm");
	$tpl_error->assign("error", $error);
	$tpl_error->output();
	exit;
}

function display_notice($notice = "" , $url = '') {
	$tpl_error = new smartTemplate("display_notice.htm");
	$tpl_error->assign("notice", $notice);
	$tpl_error->assign("url", $url);
	$tpl_error->output();
	exit;
}

function display_nopermission() {
        display_error("对不起，你的权限不足！");
        exit;
} 

function my_header($argument = array()) {
        global $tpl;
        $tpl_header = new smartTemplate("header.htm");
        $tpl_header->assign($argument);
        $result = $tpl_header->result();
        $tpl->assign("header", $result);
        return ($result);
} 

function my_footer() {
        global $tpl;
        $tpl_footer = new smartTemplate("footer.htm");
        $result = $tpl_footer->result();
        $tpl->assign("footer", $result);
        return ($result);
} 

function display_login() {
	global $url, $no_header, $no_footer;
	$tpl = new smartTemplate("display_login.htm");
	$tpl->assign("url", $url);

	if (!$no_header) {
		if (!$header_argument[title]) {
			$header_argument[title] = "Movie";
		}
		my_header($header_argument);
	}

	if (!$no_footer) {
		my_footer();
	}

	$tpl->output();
}

function html_trim($text) {
	return trim($text);
}

/**
* 检查 $value 已 assign 且不为空
*
* @access public
* @param mixd $value
* @return bool
*/
function my_isset($value) {
	if (isset($value) AND $value != "") {
		return true;
	} else {
		return false;
	}
}

/**
* 使用 $glue 将数组 $array 连接成字符串,  支持 sprintf
*
* @access public
* @param string $glue 连接符
* @param array $array
*/
function my_implode($glue = '', $array = array()) {
	$output = '';

	foreach ($array AS $k => $v) {
		$output .= sprintf($glue, $v, $v);
	}

	return $output;
}

/**
* 树状打印数据所有元素
*
* @access public
* @param array $array
*/
function print_rr($array = array()) {
	echo "<div align=\"left\">";

	echo "<pre>";

	print_r($array);

	echo "</pre>";

	echo "</div>";
}

if (!empty($_POST['url'])) {
	$url = $_POST['url'];
} else if (!empty($_GET['url'])) {
	$url = $_GET['url'];
}
if (empty($url)) {
	//$url = $_SERVER['HTTP_REFERER'];
    $url="http://admin.weixinhezi.com";
}
$url = @htmlspecialchars($url);

/**
* 页面转跳
*
* @access public
* @param string $url 转跳目标地址
* @param string $text 转跳提示
* @param integer $time 等待时间, 单位: 秒
*/
function redirect($url = "", $text = "", $time = "1") {
	if (empty($url)) {
		if ($_SERVER['HTTP_REFERER']) {
			$url = $_SERVER['HTTP_REFERER'];
		} else {
			if ($_SERVER[QUERY_STRING]) {
				$url = $_SERVER[QUERY_STRING];
			}
		}
	}
	$tpl = new smartTemplate("redirect.htm");
	$tpl->assign("text", $text);
	$tpl->assign("url", $url);
	$tpl->assign("time", $time);
	$tpl->output();
	exit;
}

// 验证是否为有效的 email 地址
function validate_email($mail = "") {
	$mail = trim($mail);
	if (!eregi("^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+\\.[a-z]{2,4}$", $mail)) {
		return false;
	} else {
		return true;
	}
}

// 验证是否为网站主页
function validate_homepage($homepage) {
	if ($homepage) {
		if (preg_match('#^www\.#si', $homepage)) {
			$homepage = "http://$homepage";
		} else if (!preg_match('#^[a-z0-9]+://#si', $homepage)) {
			$homepage = '';
		}
	}
	return $homepage;
}

// 获取文件后缀名(小写)
function get_file_ext($filename) {
	$array = @explode('.', $filename);
	if (!empty($array ) && count($array)>1) {
		$ext = array_pop($array);
	} else {
		return false;
	}
	return strtolower($ext);
}

/**
* 单位转换
*/
function get_real_size($size) {
	$kb = 1024; // Kilobyte
	$mb = 1024 * $kb; // Megabyte
	$gb = 1024 * $mb; // Gigabyte
	$tb = 1024 * $gb; // Terabyte
	if ($size < $kb) {
		return $size . " B";
	} else if ($size < $mb) {
		return round($size / $kb, 2) . " KB";
	} else if ($size < $gb) {
		return round($size / $mb, 2) . " MB";
	} else if ($size < $tb) {
		return round($size / $gb, 2) . " GB";
	} else {
		return round($size / $tb, 2) . " TB";
	}
}

/**
* 发送 nocache 头至客户端
*
* @access public
*/
function nocache_header() {
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache"); // HTTP/1.0
}

function format_chars($text = "") {
	return str_replace("  ", "", nl2br(htmlspecialchars($text)));
}

function stripslashes_array(&$array) {
	while (list($k, $v) = each($array)) {
		if (is_array($v)) {
			$array[$k] = stripslashes_array($v);
		} else {
			$array[$k] = stripslashes($v);
		}
	}
	return $array;
}

if (get_magic_quotes_gpc()) { // magic_quotes_gpc = 1
	$_GET = stripslashes_array($_GET);
	$_POST = stripslashes_array($_POST);
	$_COOKIE = stripslashes_array($_COOKIE);
}

set_magic_quotes_runtime(0);

/**
* 获取客户端 ip 地址
*
* @access public
* @return string
*/
function getip() {
	if (isset($_SERVER)) {
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
			$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		} elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
			$realip = $_SERVER["HTTP_CLIENT_IP"];
		} else {
			$realip = $_SERVER["REMOTE_ADDR"];
		}
	} else {
		if (getenv('HTTP_X_FORWARDED_FOR')) {
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('HTTP_CLIENT_IP')) {
			$realip = getenv('HTTP_CLIENT_IP');
		} else {
			$realip = getenv('REMOTE_ADDR');
		}
	}
	return $realip;
}


/**
* An easier way to do mkdirs : recursion.
*
* @access public
* @param string $strPath
* @param integer $mode
* @return bool
*/
function mkdirs($strPath = '', $mode = 777) {
	if (is_dir($strPath)) return true;
	$pStrPath = dirname($strPath);
	if (!mkdirs($pStrPath, $mode)) return false;
	return mkdir($strPath);
}

/**
* 检查首字母是否为 0-9a-zA-z
*
* @var string $initial 字母或数字
* @return string |null 返回小写或数字
*/
function validate_initial($initial = '') {
	$initial = trim($initial);

	if ($initial != '') {
		if (!ereg("^[a-zA-z0-9]{1}$", $initial) AND $initial != '0-9' AND $initial != '*') {
			display_error("请输入有效的影片名头字母或数字！");
		}

		return strtolower($initial);
	}
}

function htmldecode($encoded) {
	$encoded = str_replace("&middot;", ".", $encoded);
	$encoded = str_replace("&amp;", "&", $encoded);
	$encoded = str_replace("&quot;", "\"", $encoded);
	$encoded = str_replace("&#039;", "'", $encoded);
	$encoded = str_replace("&lt;", "<", $encoded);
	$encoded = str_replace("&gt;", ">", $encoded);
	$encoded = str_replace("&mdash;", "—", $encoded);
	$encoded = str_replace("&ldquo;", "“", $encoded);
	$encoded = str_replace("&rdquo;", "”", $encoded);
	$encoded = str_replace("&nbsp;", " ", $encoded);
	$encoded = str_replace("&hellip;", "......", $encoded);
	return $encoded;
}

/**
* highlight_search()
*
* @param  $search_words array
* @param  $string result string
* @param string $bgcolor to highlight search
* @return string with highlight
* @author Damien MARTRAIRE (ATYPIX.COM)
*/
function highlight_search($search_words, $string, $bgcolor = 'yellow') {
	foreach($search_words as $search_word) {
		$string = eregi_replace("($search_word)", '<span style="background-color: ' . $bgcolor . ';color:red;">\\1</span>', $string);
	}
	return $string;
}

function js_redirect($text, $return_url) {
	echo "
	<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
	<html xmlns=\"http://www.w3.org/1999/xhtml\">
	<head>
	<meta http-equiv=\"pragma\" content=\"nocache\" />
	<meta http-equiv=\"expires\" content=\"Mon, 26 Jul 1997 05:00:00 GMT\">
	<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
	<body>
	<script>
	alert(\"$text\");
	window.location.href=\"$return_url\";
	</script>
	</body>
	</html>
	";
	exit;
}

function dateDiff($diff) {
	if ($diff < 0) {
		// error condition
		return false;
	}
	$weeks = $days = $hours = $minutes = $seconds = 0; # initialize vars
	if ($diff % 604800 > 0) {
		$rest1 = $diff % 604800;
		$weeks = ($diff - $rest1) / 604800; # seconds a week
		if ($rest1 % 86400 > 0) {
			$rest2 = ($rest1 % 86400);
			$days = ($rest1 - $rest2) / 86400; # seconds a day
			if ($rest2 % 3600 > 0) {
				$rest3 = ($rest2 % 3600);
				$hours = ($rest2 - $rest3) / 3600; # seconds an hour
				if ($rest3 % 60 > 0) {
					$seconds = ($rest3 % 60);
					$minutes = ($rest3 - $seconds) / 60; # seconds a minute
				} else {
					$minutes = $rest3 / 60;
				}
			} else {
				$hours = $rest2 / 3600;
			}
		} else {
			$days = $rest1 / 86400;
		}
	} else {
		$weeks = $diff / 604800;
	}
	$string = array();
	if ($weeks > 1) {
		$string[] = "{$weeks}周";
	} elseif ($weeks == 1) {
		$string[] = "1周";
	}
	if ($days > 1) {
		$string[] = "{$days}天";
	} elseif ($days == 1) {
		$string[] = "1天";
	}
	if ($hours > 1) {
		$string[] = "{$hours}小时";
	} elseif ($hours == 1) {
		$string[] = "1小时";
	}
	if ($minutes > 1) {
		$string[] = "{$minutes}分钟";
	} elseif ($minutes == 1) {
		$string[] = "1分钟";
	}
	if ($seconds > 1) {
		$string[] = "{$seconds}秒";
	} elseif ($seconds == 1) {
		$string[] = "1秒";
	}
	// join together all the strings in the array above except the last element
	$text = join(', ', array_slice($string, 0, sizeof($string)-1)) . ", and ";
	$text .= array_pop($string); # put the last one on after the and
	return array($text, $weeks, $days, $hours, $minutes, $seconds);
}

function getDongtaiTimeStr($timestr){
	$str='';
	$time = strtotime($timestr);
	$now = time();
	$distance = $now - $time;
	if($distance/60 < 1){
		if($distance<0)$distance=1;
		$str = '约'.$distance.'秒前';
	}else if($distance/60 >1 && $distance/3600 < 1){
		$str = '约'.intval($distance/60).'分钟前';
	}else if($distance/3600 >1 && $distance/(3600*24) < 1){
		$str = intval($distance/3600).'小时前';
	}else if($distance/(3600*24) >1 && $distance/(3600*24*7) < 1){
		$str = intval($distance/(3600*24)).'天前';
	}else if($distance/(3600*24*7) >1 && $distance/(3600*24*7*30) < 1){
		$str = intval($distance/(3600*24*7)).'周前';
	}else if($distance/(3600*24*7*30) >1 && $distance/(3600*24*7*30*12) < 1){
		$str = intval(3600*24*7*30).'月前';
	}else if($distance/(3600*24*7*30*12) >1 ){
		$str = intval($distance/(3600*24*7*30*12)).'年前';
	}
	return  $str;
}

// fetch url content and save as static file
function url_to_file($url, $output_file, $retry = 1) {
	// $cmd = "wget $url -t 3 -O $output_file -a /var/log/url_to_file.log -q";
	$cmd = "wget $url -t 3 -O $output_file";
	exec($cmd);
	$x = $retry;
	$x++;

	if (file_exists($output_file) AND filesize($output_file) > 512) {
		return true;
	} else {
		if ($x > 3) {
			return false;
		}
		// retry
		url_to_file($url, $output_file, $x);
	}
}

/*
* 因为IE和FF内置编码的问题，导致提交后的数据编码不一致
* FF提交后会自动转成UTF-8，而IE则不会
* 该函数通过判断浏览器类型而来决定是否需要对字符编码
*/
function ajax_encode($request_string) {
	$request_string = html_trim($request_string);
	if (preg_match("/MSIE/i", $_SERVER["HTTP_USER_AGENT"])) {
		$request_string = mb_convert_encoding($request_string, "utf-8", "gbk");
	}
	return $request_string;
}

/*
** 获得随机数
*/
function random($length, $numeric = 0) {
	mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function trim_p($str) {
	$str = trim($str);
	while (substr($str, 0, 3) == '<p>') {
		$str = substr($str, 3);
	}
	while (substr($str, -4) == '</p>') {
		$str = substr($str, 0, -4);
	}
	return $str;
}

function cutstr($string, $length, $ext='...') {//限制字符串长度
	$strcut ='';
	$ord = 0;
	if(strlen($string) > $length) {
		for($i = 0; $i < $length - 3; $i++) {
			$ord = ord($string[$i]);
			if($ord > 127){
				if(mb_strlen($string[$i].$string[$i+1].$string[$i+2], 'utf-8')==1){
					$strcut .= $string[$i].$string[++$i].$string[++$i];
				}else{
					$strcut .=$string[$i];
				}
			}else{
				//修正大写字母宽度
				if($ord>64 && $ord<91 || $ord == 126){
					$length -= 1;
					$strcut .=$string[$i];
				}else{
					$strcut .=$string[$i];
				}
			}
		}
		return $strcut.$ext;
	} else {
		return $string;
	}
}

function phpEscape($str) { 
	$ar = "";
	$chars = preg_split('//', $str, -1 ) ; 
	$n = count( $chars )-1 ; 
	for($i=1;$i<$n ;$i++ ) { 
		$char = $chars[$i]; 
		$ord = ord( $char ); 
		if( $ord<=0x7F){ 
			$ar .= rawurlencode( $char ); 
		}else{ 
			$tmpString = bin2hex( iconv( 'gbk' ,"UCS-2",$chars[$i].$chars[$i+1] ) ); 
			//判断平台，不是windows的话，高位低位置换
			if (!eregi("WIN",PHP_OS)){
                $tmpString=substr($tmpString,2,2).substr($tmpString,0,2);
            }
            $tmpString="%u".$tmpString;
			$ar .= $tmpString; 
			$i++; 
		} 
	}
	return $ar; 
}

function execSocketCmd($server,$port,$cmd) {
	$sock = @fsockopen($server, $port, $errno, $errstr, 30);
	if (!$sock) {
		//return "$errstr ($errno)";
		return false;
	}
	@fputs($sock, $cmd);
	$body = @fread($sock, 4096);
	@fclose($sock);
	$body = iconv('gbk','utf-8',$body);
	return $body;
}

// 获取用户所在数据库名
function getDatabaseUser($userid) {                           
	//$no = floor(hexdec(substr(md5($userid), 0, 2))/64);
	return " xiaozu_user";      
}
// 获取用户所在数据库表名
function getTableUser($userid) {
	$no = hexdec(substr(md5($userid), 2, 2));
	return "user$no";
	//return "user0";
}

// 获取用户-话题所在数据库名
function getDatabaseUserThread($id) {
	//$no = floor(hexdec(substr(md5($id), 0, 2))/64);
	return " xiaozu";
}
// 获取用户-话题所在数据库表名
function getTableUserThread($id) {
	//$no = hexdec(substr(md5($id), 2, 2));
	//return "user_thread$no";
	return "user_thread";
}

// 获取用户-小组所在数据库名
function getDatabaseUserGroup($id) {
	return " xiaozu";
}
// 获取用户-小组所在数据库表名
function getTableUserGroup($id) {
	//$no = hexdec(substr(md5($id), 2, 2));
	//return "user_group$no";
	return "user_group";
}

// 获取用户-用户所在数据库名
function getDatabaseUserUser($id) {
	return " xiaozu";
}
// 获取用户-用户所在数据库表名
function getTableUserUser($id) {
	//$no = hexdec(substr(md5($id), 2, 2));
	//return "user_user$no";
	return "user_user";
}

function ImageResize($srcFile,$toW,$toH,$toFile="")
{
    if($toFile==""){ $toFile = $srcFile; }
    $info = "";
    $data = GetImageSize($srcFile,$info);
    switch ($data[2])
    {
        case 1:
            if(!function_exists("imagecreatefromgif")){
                echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！<a href='javascript:go(-1);'>返回</a>";
                exit();
            }
            $im = ImageCreateFromGIF($srcFile);
            break;
        case 2:
            if(!function_exists("imagecreatefromjpeg")){
                echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>";
                exit();
            }
            $im = ImageCreateFromJpeg($srcFile);
            break;
        case 3:
            $im = ImageCreateFromPNG($srcFile);
            break;
    }
    $srcW=ImageSX($im);
    $srcH=ImageSY($im);
    $toWH=$toW/$toH;
    $srcWH=$srcW/$srcH;
    if($toWH<=$srcWH){
        $ftoW=$toW;
        $ftoH=$ftoW*($srcH/$srcW);
    }
    else{
        $ftoH=$toH;
        $ftoW=$ftoH*($srcW/$srcH);
    }
    if($srcW>$toW||$srcH>$toH)
    {
        if(function_exists("imagecreatetruecolor")){
            @$ni = ImageCreateTrueColor($ftoW,$ftoH);
            if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
            else{
                $ni=ImageCreate($ftoW,$ftoH);
                ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
            }
        }else{
            $ni=ImageCreate($ftoW,$ftoH);
            ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
        }
        if(function_exists('imagejpeg')) ImageJpeg($ni,$toFile);
        else ImagePNG($ni,$toFile);
        ImageDestroy($ni);
    }
    ImageDestroy($im);
}
?>